package com.insta.formation.calendar.dao.impl;


import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;


import com.insta.formation.calendar.dao.ICalendarDao;
import com.insta.formation.calendar.model.Calendar;
import com.insta.formation.calendar.model.Event;
import com.insta.formation.calendar.model.Person;


/**
 *  @See {@link ICalendarDao}
 */

public class CalendarDaoImpl extends GenericDaoImpl<Calendar, Integer> implements ICalendarDao
{

	public CalendarDaoImpl(Class<Calendar> type) {
		super(type);
	}


	/**
	 *  @See {@link ICalendarDao}
	 */
	public Calendar findByName(String name) {
		Criteria crit =
				 getSession().createCriteria(Calendar.class).add(Restrictions.eq("name",
						 name));
		crit.setMaxResults(1);
		Calendar cal = (crit.list().isEmpty() ? null : (Calendar) crit.list().get(0));
		return cal;
	}

	/**
	 *  @See {@link ICalendarDao}
	 */
	@SuppressWarnings("unchecked")
	public Event readEvent(String calendarName, String eventName) {
		String query = "select event " +
				"from Calendar calendar inner join calendar.events event " +
				"where calendar.name=:calendar_name and event.name=:event_name";
		Query q = getSession().createQuery(query);
		q.setString("calendar_name", calendarName);
		q.setString("event_name", eventName);

		List<Event> events = q.list();

		return ((!events.isEmpty()) ? events.get(0) : null);
	}


	/**
	 *  @See {@link ICalendarDao}
	 */
	public void deleteEvent(Calendar calendar, Event event) {
		getSession().beginTransaction();
		calendar.getEvents().remove(event);
		getSession().update(calendar);
		getSession().delete(event);
		getSession().getTransaction().commit();
	}


	/**
	 *  @See {@link ICalendarDao}
	 */
	public void deleteGuestEvent(Event event, Person guest) {
		getSession().beginTransaction();
		event.getGuests().remove(guest);
		getSession().update(event);
		getSession().getTransaction().commit();
	}

	/**
	 *  @See {@link ICalendarDao}
	 */
	public void updateEvent(Event event) {
		getSession().beginTransaction();
		getSession().update(event);
		getSession().getTransaction().commit();
	}
	
}
